package com.kedacom.ctsp.authz.oauth2.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kedacom.ctsp.authz.entity.AuthUser;
import com.kedacom.ctsp.authz.exception.UnauthorizedException;
import com.kedacom.ctsp.authz.oauth2.core.ErrorType;
import com.kedacom.ctsp.authz.security.AuthzSecurityProperties;
import com.kedacom.ctsp.authz.security.captcha.CaptchaService;
import com.kedacom.ctsp.authz.security.provider.TokenManager;
import com.kedacom.ctsp.authz.security.provider.UserBean;
import com.kedacom.ctsp.web.controller.message.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @页面登录后，跳转到登录前拦截的url
 * @com.kedacom.ctsp.authz.oauth2.provider
 * @fenghaiju
 * @2018/5/15-14:29
 * @cloud-rbac-oauth2
 **/
@Slf4j
public class OAuth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired(required = false)
    private CaptchaService captchaService;
    @Value("${server.session.timeout:86400}")
    private int expireTime;
    @Autowired
    private TokenManager tokenManager;
    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        HttpSession session = request.getSession(true);
        session.setMaxInactiveInterval(expireTime);
        if (savedRequest == null) {
            // 清空登录失败次数
            if (captchaService != null) {
                captchaService.clearLoginWrongTimes(request.getSession());
            }
            com.kedacom.ctsp.authz.entity.Authentication userAuthentication
                    = com.kedacom.ctsp.authz.entity.Authentication.current().orElseThrow(UnauthorizedException::new);

            AuthUser authUser = userAuthentication.getUser();
            // 保存token
            Object authObj = request.getAttribute("authUser");
            if (authObj instanceof UserBean) {
                UserBean userBean = (UserBean) authObj;
                if (org.apache.commons.lang3.StringUtils.isNotBlank(userBean.getAccessToken())) {
                    authUser = tokenManager.loginDirectly(userBean.getUsername(), userBean.getAccessToken());
                }
            }

            // 返回值
            ResponseMessage<AuthUser> ok = ResponseMessage.ok(authUser);

            response.getWriter().println(JSONObject.toJSON(ok));
            //登录成功后，直接跳转
        } else {
            String targetUrlParameter = getTargetUrlParameter();
            if (isAlwaysUseDefaultTargetUrl()
                    || (targetUrlParameter != null && StringUtils.hasText(request
                    .getParameter(targetUrlParameter)))) {
                requestCache.removeRequest(request, response);
                super.onAuthenticationSuccess(request, response, authentication);

                return;
            }
            clearAuthenticationAttributes(request);
            String targetUrl = savedRequest.getRedirectUrl();
            log.info("Redirecting to DefaultSavedRequest Url: " + targetUrl);
            // 页面跳转
            ResponseMessage<String> responseMessage = ResponseMessage.ok(targetUrl);
            responseMessage.setMessage(targetUrl);
            responseMessage.setCode(String.valueOf(ErrorType.REDIRECT_URI.code()));
            response.getWriter().println(JSONObject.toJSON(responseMessage));
            //  getRedirectStrategy().sendRedirect(request, response, targetUrl);
        }
    }

    public void setRequestCache(RequestCache requestCache) {
        this.requestCache = requestCache;
    }
}
